package javango.contrib.admin.api;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javango.contrib.admin.MetaOptions;
import javango.contrib.hibernate.HibernateUtil;
import javango.db.Manager;
import javango.db.Managers;

import org.hibernate.mapping.Property;

import com.google.inject.Inject;

/**
 * Subclasses should override the constructor calling addClass or addClasses to build the list of classes that can be managed via the admin interface
 * @param clazz
 */
public class CustomAdminOptions implements AdminOptions {

	List<Class> classList = new ArrayList<Class>();
	
	HibernateUtil hibernateUtil;
	Managers managers;
	String appName;
	
	@Inject
	public CustomAdminOptions(Managers managers, HibernateUtil hibernateUtil) {
		this.hibernateUtil = hibernateUtil;
		this.managers = managers;
	}

	protected void addClasses(Class... classes) {
		for(Class c : classes) {
			addClass(c);
		}
	}

	
	protected void addClass(Class clazz) {
		this.classList.add(clazz);
	}
	
	public Class getClassMapping(String entityName) {
		for(Class c : classList) {
			if (c.getName().equals(entityName)) {
				return c;
			}
		}
		return null;
	}

	public Iterator<Class> getClassMappings() {
		return classList.iterator();
	}

	public String getLinkProperty(Class clazz) {
		return null;
	}

	public ModelAdmin getModelAdmin(Class model) {
		BaseModelAdmin ma = new BaseModelAdmin();
		ma.setFields(getFieldList(model));
		ma.setListDisplay(ma.getFields());
		ma.setManager(getManager(model));
		return ma;
	}
	
	private Manager<?> getManager(Class entityClass) {
		return managers.forClass(entityClass);
	}

	private String[] getFieldList(Class clazz) {
		List<String> property_list = new ArrayList<String>();
		
		Iterator<Property> i = hibernateUtil.getConfiguration().getClassMapping(clazz.getName()).getPropertyIterator();
		while (i.hasNext()) {
			Property p = i.next();
			property_list.add(p.getName());
		}
		return property_list.toArray(new String[]{});
	}

	public String getIndexTemplate() {
		return "javango/contrib/admin/templates/index.ftl";
	}

	public String getAppName() {
		return appName;
	}

	public AdminOptions setAppName(String appName) {
		this.appName = appName;
		return this;
	}
}
